package md.mru.frontend.convertors;

import md.mru.frontend.beans.ApplicationStateBean;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

/**
 * @author sergiu.marin
 * @since 31.03.2014
 */
@ManagedBean
@SessionScoped
public class SelectComponentConverter implements Converter {

    @ManagedProperty(value = "#{applicationStateBean}")
    private ApplicationStateBean applicationStateBean;

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
        if (uiComponent.getId().equals("nationality")) {
            return applicationStateBean.getNationalityByName(s);
        } else if (uiComponent.getId().equals("family-status")) {
            return applicationStateBean.getFamilyStatusByName(s);
        } else if (uiComponent.getId().equals("sex")) {
            if (s.equals("Male")) {
                return 0;
            } else if (s.equals("Female")) {
                return 1;
            }
        }
        return "";
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
        if (o != null) {
            if (uiComponent.getId().equals("nationality")) {
                return applicationStateBean.getNationalityById((Long) o);
            } else if (uiComponent.getId().equals("family-status")) {
                return applicationStateBean.getFamilyStatusById((Long) o);
            } else if (uiComponent.getId().equals("sex")) {
                if (o == 0) {
                    return "Male";
                } else if (o == 1) {
                    return "Female";
                }
            }
        }
        return "";
    }

    public void setApplicationStateBean(ApplicationStateBean applicationStateBean) {
        this.applicationStateBean = applicationStateBean;
    }
}
